//
// Created by rany on 1/18/17.
//
#include <stdlib.h>
#include <string.h>

#include "queue.h"

pqueue createQueue()
{
    pqueue queue;

    queue = (pqueue) malloc(sizeof(queue_t));

    if (queue != NULL) {
        queue->head = NULL;
        queue->rear = NULL;
        queue->length = 0;
    }

    return queue;
}

void enQueue(pqueue queue, message_t data)
{
    pnode tmp;

    if (queue == NULL) {
        return;
    }

    tmp = (pnode) malloc(sizeof(qnode_t));

    if (tmp == NULL) {
        return;
    }

    memcpy(&(tmp->data), &data, sizeof(data));

    tmp->next == NULL;

    if (queue->head == NULL) {
        queue->head = queue->rear = tmp;
    } else {
        queue->rear = tmp->next;
        queue->rear = tmp;
    }

    ++queue->length;
}

message_t deQueue(pqueue queue)
{
    message_t msg;
    pnode node;

    memset(&msg, 0, sizeof(message_t));

    if (queue == NULL) {
        return msg;
    }

    memcpy(&msg, &queue->head->data, sizeof(message_t));

    node = queue->head;
    queue->head = node->next;

    --queue->length;
    free(node);

    return msg;
}

message_t firstQueue(pqueue queue)
{
    message_t msg;
    pnode node;

    memset(&msg, 0, sizeof(message_t));

    if (queue == NULL) {
        return msg;
    }

    memcpy(&msg, &queue->head->data, sizeof(message_t));

    return msg;
}

void destroyQueue(pqueue * queue)
{
    pnode node, node1;

    if (queue != NULL) {
        node = (*queue)->head;

        while(node != NULL ) {
            node1 = node->next;
            free(queue);
            node = node1;
        }

        free(queue);
        queue = NULL;
    }
}

int isEmpty(pqueue queue)
{
    return queue == NULL || queue->length == 0;
}
